import { Service } from 'egg';
import utils from '~/utils';
import dayjs from 'dayjs';

export default class TestService extends Service {

    async list() {
        const { ctx } = this;
        const {
            page_num = 1,
            page_size = 15,
        } = ctx.request.body;

        let whereMap = {};
        let orderMap = <any[]>[];

        orderMap.push(['id', 'desc']);
        // orderMap.push(['status', 'desc']);

        let { count, rows } = utils.text.toRaw(await ctx.model.Users.findAndCountAll({
            // 只查询某些需要的字段
            // attributes: [
            //     'id',
            //     'name',
            //     'age'
            // ],
            // 排除某些字段其他全部查
            // attributes: {
            //     exclude: ['password'],
            // },
            // 关联查询
            // include: { model: this.ctx.model.Users, as: 'users' },
            where: {
                ...whereMap
            },
            // 查询结构进行排序
            order: orderMap,
            // 分页
            offset: (page_num - 1) * page_size,
            limit: page_size
        }));

        let data = {};
        data['list'] = rows;
        data['page_amount'] = Math.ceil(count / page_size);
        data['page_num'] = page_num;
        data['page_size'] = page_size;
        data['total'] = count;

        return data;
    }

    async create() {
        const { ctx } = this;
        const {
            name,
            age
        } = ctx.request.query; // ctx.request.body

        const { Op } = ctx.app.Sequelize;

        // 事务
        const t = await ctx.model.transaction();
        try {

            const user = await ctx.model.Users.create({
                name,
                age,
                created_at: dayjs().valueOf()
            }, {
                transaction: t
            });

            await t.commit();

            return { user };
        } catch (err: any) {
            ctx.logger.error(err);
            await t.rollback();
            throw new Error(err.message);
        }
    }

    async update() {
        const { ctx } = this;
        const {
            id,
            name,
            age
        } = ctx.request.query; // ctx.request.body

        const { Op } = ctx.app.Sequelize;

        const user = await ctx.model.Users.findByPk(id);
        if (!user) {
            throw new Error('user not found');
        }

        // 事务
        const t = await ctx.model.transaction();
        try {

            await ctx.model.Users.update({
                id,
                name,
                age,
                updated_at: dayjs().valueOf()
            }, {
                where: {
                    id
                },
                transaction: t
            });

            await t.commit();

            return { user };
        } catch (err: any) {
            ctx.logger.error(err);
            await t.rollback();
            throw new Error(err.message);
        }
    }

    async detail(id) {
        const { ctx } = this;

        const { Op } = ctx.app.Sequelize;

        let info = utils.text.toRaw(await ctx.model.Users.findOne({
            // 查询指定字段
            attributes: [
                'id',
                'name',
                'age'
            ],
            // 关联查询
            // include: { model: this.ctx.model.Users, as: 'users' },
            // 条件查询
            where: {
                id
            }
        }));

        return info;
    }

    async delete(id) {
        const { ctx } = this;

        const user = await ctx.model.Users.findByPk(id);
        if (!user) {
            throw new Error('User not found');
        }

        await ctx.model.Users.destroy({
            where: {
                id
            }
        });
    }
}
